#include <hd_oled.h>
#include <pd_gpio.h>
#include <pd_i2c_hd.h>
#include <hd_oled_protocol_i2c.h>
#include <delay.h>
#include <hd_key.h>
#include <pd_iwdg.h>
#include <pd_spi_io.h>
#include <stddef.h>
#include <pd_spi_hd.h>
#include <hd_oled_protocol_spi.h>
#include "main.h"


#define ARRAY_SIZE(x)       sizeof(x) / sizeof(x[0])
#define USE_HARDWARE_SPI    1
#define USE_HARDWARE_I2C    1
OLED oled;

uint8_t count = 0;

extern void SystemClock_Config(void);

void oled_instance(OLED *oled);

int main(void) {

    SystemClock_Config();

    NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_2);

    oled_instance(&oled);

    GPIO keyGPIO;
    GPIO_constructor(&keyGPIO, GPIOA, LL_GPIO_PIN_0);

    Key key;
    Key_constructor(&key, &keyGPIO);
    Key_init(&key);

    OLED_printf(&oled, 0, 0, "IWDG TEST");
    OLED_refresh(&oled);

    IndepWDG iwdg;
    IndepWDG_constructor(&iwdg, IWDG, LL_IWDG_PRESCALER_32, 3000);
    WDG *wdg = (WDG *) &iwdg;

    // Reset signal from IWDG
    if (WDG_isReset(wdg)) {
        LL_RCC_ClearResetFlags();
        OLED_printf(&oled, 0, 16, "IWDG RST");
        OLED_refresh(&oled);
        delay_ms(500);
        OLED_printf(&oled, 0, 16, "        ");
        OLED_refresh(&oled);
        delay_ms(100);
    } else {
        // Reset signal from system
        OLED_printf(&oled, 0, 16, "RST");
        OLED_refresh(&oled);
        delay_ms(2000);
        OLED_printf(&oled, 0, 16, "   ");
        OLED_refresh(&oled);
        delay_ms(500);
    }

    // Init Watchdog
    WDG_init(wdg);

    while (1) {
        Key_getNum(&key);   // delay feed dogs time

        WDG_feedDogs(wdg);  // feed dogs

        OLED_printf(&oled, 0, 48, "FEED IWDG");
        OLED_refresh(&oled);
        delay_ms(2500);
        OLED_printf(&oled, 0, 48, "         ");
        OLED_refresh(&oled);
        delay_ms(400);
    }

}


void oled_instance(OLED *oled) {
    // I2C gpio init
    static GPIO oledSckGPIO, oledSdaGPIO;
    GPIO_constructor(&oledSckGPIO, GPIOB, LL_GPIO_PIN_10); // I2Cx_SCK
    GPIO_constructor(&oledSdaGPIO, GPIOB, LL_GPIO_PIN_11); // I2Cx_SDA

#ifdef USE_HARDWARE_I2C
    static I2CHardware i2c2;
    I2CHardware_constructor(&i2c2, I2C2, &oledSckGPIO, &oledSdaGPIO);
#elif USE_SIMULATE_I2C
    static I2CSimulate i2c2;
    I2CSimulate_constructor(&i2c2, &oledSckGPIO, &oledSdaGPIO);
#endif
    I2C_init((I2C *) &i2c2);

    // OLED protocol of I2C
    static OLEDProtocolI2C oledProtocolI2c;
    OLEDProtocolI2C_constructor(&oledProtocolI2c, (I2C *) &i2c2);

    // OLED font instance.
    static OLEDFont oledFont;
    OLEDFont_contructor(&oledFont, NULL);

    // OLED instance of 4-PIN(I2C)
    OLED_constructor(oled, (OLEDProtocol *) &oledProtocolI2c, &oledFont);

    OLED_init(oled);

    OLED_clear(oled);
    OLED_refresh(oled);
}


